package server.multiServlet;

import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpProtocolUtil;
import server.HttpServlet;
import server.Request;
import server.Response;

import java.io.*;
import java.util.List;

@Getter
@Setter
public class Context implements Container {

    private String name;

    private String path;

    private String docPath;

    private List<Wrapper> wrappers= Lists.newArrayList();

    private ClassLoader classLoader;

    public Context(String path, String docPath) {
        this.path = path;
        this.docPath = docPath;
    }


    @Override
    public void init() {
        classLoader = new ClassLoader(this.name + File.separator + docPath);

        // 解析相应的web.xml
        try {
            loadServlet();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void execute(Request request, Response response) {
        try {

            String realUrl = request.getUrl().substring(path.length());
            for (Wrapper wrapper : wrappers) {
                if (wrapper.getUrlPattern().equals(realUrl)) {
                    wrapper.getInstance().service(request, response);
                    return;
                }
            }
            response.output(HttpProtocolUtil.getHttpHeader404());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadServlet() throws FileNotFoundException {
        /**
         * 加载解析web.xml，初始化Servlet
         */

        InputStream resourceAsStream = new FileInputStream(new File(this.name + File.separator + docPath + File.separator + "web.xml"));
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                Class aClass =classLoader.findClass(servletClass);
                HttpServlet servlet = (HttpServlet) aClass.newInstance();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                Wrapper wrapper = new Wrapper(urlPattern, servlet);

                this.wrappers.add(wrapper);
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


}
